<?php

namespace PHPSpring\Type;

class Json implements \JsonSerializable {

  private $obj;


  public function __construct ($json) {
    if (empty($json)) {
      $this->obj = [];
    } else {
      $obj = json_decode($json, true);
      if (is_null($obj)) {
        $this->obj = [];
      } else {
        $this->obj = $obj;
      }
    }
  }

  public function jsonSerialize () {
    return @json_encode($this->obj);
  }

  public function &get () {
    return $this->obj;
  }

  public function set ($val = []) {
    if (is_string($val)) {
      $this->obj = json_decode($val, true);
    } elseif (is_array($val)) {
      $this->obj = $val;
    } elseif (is_scalar($val)) {
      $this->obj = [$val];
    } else {
      $this->obj = $val;
    }
  }


  public function __toString () {
    return $this->jsonSerialize();
  }

}
